using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using AutoMapper;
using HuiLian.Common.Input;
using HuiLian.Common.Output;
using HuiLian.Model.Platform;
using HuiLian.Repository.Platform;
using HuiLian.Service.Platform.Repairledget.Input;
//using HuiLian.Service.Platform.Repairledget.Output;
using HuiLian.Common.Attributes;
using HuiLian.Common;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Crypto;
using System.Text;

namespace HuiLian.Service.Platform.Repairledget
{
    /// <summary>
    /// 修漏作业记录服务
    /// </summary>
    public class RepairledgetService : IRepairledgetService
    {
        private readonly IMapper _mapper;
        private readonly IRepairledgetRepository _repairledgetRepository;

        public RepairledgetService(IMapper mapper, IRepairledgetRepository repairledgetRepository)
        {
            _mapper = mapper;
            _repairledgetRepository = repairledgetRepository;
        }

        /// <summary>
        /// 获取修漏作业记录信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _repairledgetRepository.GetAsync(id);
            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 查询修漏作业记录信息
        /// </summary>
        /// <param name="input">分页信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageAsync(PageInput<RepairledgetEntity> input)
        {
            //var key = input.Filter?.Label;

            var list = await _repairledgetRepository.Select
            .WhereDynamicFilter(input.DynamicFilter)
            //.WhereIf(key.NotNull(), a => a.Path.Contains(key) || a.Label.Contains(key))
            .Count(out var total)
            .OrderBy(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync();

            var data = new PageOutput<RepairledgetEntity>()
            {
                List = list,
                Total = total
            };

            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 添加修漏作业记录信息
        /// </summary>
        /// <param name="input">修漏作业记录信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> AddAsync(RepairledgetAddInput input)
        {
            var entity = _mapper.Map<RepairledgetEntity>(input);
            var id = (await _repairledgetRepository.InsertAsync(entity)).Id;

            return ResponseOutput.Result(id > 0);
        }

        /// <summary>
        /// 更新修漏作业记录信息
        /// </summary>
        /// <param name="input">修漏作业记录信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdateAsync(RepairledgetUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }

            var entity = await _repairledgetRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("数据不存在！");
            }

            _mapper.Map(input, entity);
            await _repairledgetRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 删除修漏作业记录信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> DeleteAsync(long id)
        {
            var result = false;
            if (id > 0)
            {
                result = (await _repairledgetRepository.DeleteAsync(m => m.Id == id)) > 0;
            }

            return ResponseOutput.Result(result);
        }

        /// <summary>
        /// 软删除修漏作业记录信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> SoftDeleteAsync(long id)
        {
            var result = await _repairledgetRepository.SoftDeleteAsync(id);
            return ResponseOutput.Result(result);
        }

        /// <summary>
        /// 批量软删除修漏作业记录信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> BatchSoftDeleteAsync(long[] ids)
        {
            var result = await _repairledgetRepository.SoftDeleteAsync(ids);

            return ResponseOutput.Result(result);
        }

        /// <summary>
        /// 添加列表
        /// </summary>
        /// <param name="repairledgets"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> AddListAsync(List<RepairledgetEntity> repairledgets)
        {
            var entitys = await _repairledgetRepository.Select.ToListAsync();
            List<RepairledgetEntity> addList = new List<RepairledgetEntity>();
            foreach (var repairledget in repairledgets)
            {
                var entity = entitys.Where(p => p.任务编号 == repairledget.任务编号).FirstOrDefault();
                if (entity == null) addList.Add(repairledget);
            }

            if (addList.Count > 0)
            {
                var count = (await _repairledgetRepository.InsertAsync(addList)).Count;
                return ResponseOutput.Result(count > 0);
            }
            return ResponseOutput.Result(true);
        }

        /// <summary>
        /// 数据匹配
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> DataPiPei()
        {
            StringBuilder sql = new StringBuilder("update repairledget set 管段编号=t.管段编号,\"漏点ID\"=t.\"实体ID\" ");
            sql.AppendLine(" from( select r.任务编号,l.\"实体ID\",l.管段编号 from repairledget r ");
            sql.AppendLine(" join leakpoint l on l.安装地址=r.\"发生地址\") as t ");
            sql.AppendLine(" where repairledget.任务编号=t.任务编号 ");

            var count = await _repairledgetRepository.Orm.Ado.ExecuteNonQueryAsync(sql.ToString());//.WithSql(sql.ToString()).ExecuteAffrows;
            return ResponseOutput.Result(count > 0);
        }

        /// <summary>
        /// 更新管线的维修次数
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdateCount()
        {
            string sql = "update pipe set 维修次数=t.数量 from (select 管段编号,count(*) as 数量 from repairledget where 管段编号 is not null group by 管段编号)as t where  pipe.管段编号=t.管段编号";
            await _repairledgetRepository.Orm.Ado.ExecuteNonQueryAsync(sql);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 更新普查年份
        /// </summary>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdatePuChaYear()
        {
            string sql = "update leakpoint set 普查年份 = cast(to_char(普查时间, 'yyyy') as int) ";
            await _repairledgetRepository.Orm.Ado.ExecuteNonQueryAsync(sql);
            return ResponseOutput.Ok();
        }
    }
}
